import Vue from 'Vue'
import Router from 'vue-router'
import mainRouter from './mainRouter'
import store from '@/store'

import { checkUserToken } from "@/api/front/user"

Vue.use(Router)
let routes = []
routes = routes.concat(mainRouter)

const router = new Router({
    mode: 'history',
    routes: routes
})

//路由守卫
let beforeEach = async function(to, from, next) {
    if (to.path.match(/^\/user/) != null) {
        store.commit('user/setUserType', 0)
        next()
    } else if (to.path.match(/^\/admin/) != null) {
        store.commit('user/setUserType', 1)
        next()
    } else if (to.path.match(/^\/admPage/g) != null) {
        store.commit('user/setUserType', 1)
        next()
    } else if (to.path.match(/^\/uIndex/) != null) {
        store.commit('user/setUserType', 0)
        checkUserToken({}, (res) => {
            if (res.code == 200) {
                store.commit('user/setUserMsg', res.data)
                store.commit('user/setUserIsLegal', true)
                next()
            } else {
                store.commit('user/setUserMsg', {})
                store.commit('user/setUserIsLegal', false)
                next()
            }
        })
    } else if (to.path.match(/^\/publish/) != null) {
        store.commit('user/setUserType', 0)
        checkUserToken({}, (res) => {
            if (res.code == 200) {
                store.commit('user/setUserMsg', res.data)
                store.commit('user/setUserIsLegal', true)
                next()
            } else {
                store.commit('user/setUserMsg', {})
                store.commit('user/setUserIsLegal', false)
                next({ path: "/user/login" })
            }
        })
    }
}
router.beforeEach(beforeEach)
export default router